package linestrategy

import (
	"codejy/analysis/lineanalysis"
	"codejy/globalfunc"
	"codejy/store"
	"codejy/structdef"
	"strings"
)

// 定义策略
type FuncCallMultiStrategy struct{}

// // 注册策略
func init() {
	RegisterStrategy(&FuncCallMultiStrategy{})
	globalfunc.RegisterFuncAll("FunctionCallMulti", FunctionCallMulti)
}

// 判断
func (f *FuncCallMultiStrategy) getId() int {
	return lineanalysis.FunctionCallMulti
}

func (f *FuncCallMultiStrategy) Execute(threadStore *structdef.ThreadStore) {
	FunctionCallMulti(threadStore, threadStore.Code.LineContent)
}
func FunctionCallMulti(threadStore *structdef.ThreadStore, code string) string {

	//获取第一个(的位置
	index := strings.Index(code, "(")
	var num = 1
	for i := index + 1; i < len(code); i++ {
		if code[i] == '(' {
			num++
		} else if code[i] == ')' {
			num--
		}
		if num == 0 {
			//函数名
			funName := code[0 : i+1]
			funName, funParams := SubFunctionCallNameAndParam(funName)
			FunctionCallExecute(threadStore, funName, funParams)
			//获取函数返回值
			variable1, p := store.GetVariable(threadStore, funName)
			if len(code)-1 != i {
				if !p {
					panic(funName + "函数调用失败,请检查函数是否存在返回值,否则后面的()将无法运行 ")
				}
				//替换函数调用
				code = strings.Replace(code, funName+"("+strings.Join(funParams, ",")+")", variable1.Value, 1)
				index = strings.Index(code, "(")
				i = index
				num = 1
			} else {
				return variable1.Value //返函数的返回值
			}
		}
	}
	return ""
}
